﻿using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using YJKCodeBase.WinForm;
using YJKView;

namespace WallCreateAndEdit.WallModule
{
	[Regeneration(RegenerationOption.Manual)]
	[Transaction(TransactionMode.Manual)]
	public class CmdSetWallJoin : IExternalCommand
	{
		[DllImport("user32.dll", EntryPoint = "SendMessageA")]
		public static extern int SendMessage(IntPtr hwnd, int wMsg, IntPtr wParam, IntPtr lParam);

		public Result Execute(ExternalCommandData cmdData, ref string msg, ElementSet elems)
		{
			if (CmdSetWallJoin._hWndRevit == null)
			{
				Process currentProcess = Process.GetCurrentProcess();
				IntPtr mainWindowHandle = currentProcess.MainWindowHandle;
				CmdSetWallJoin._hWndRevit = new WindowHandle(mainWindowHandle);
			}
			CmdViewType types = (CmdViewType)11;
			if (SwitchView.SetUsableView(types, cmdData) != Autodesk.Revit.UI.Result.Succeeded)
			{
				return Autodesk.Revit.UI.Result.Failed;
			}
			Document document = cmdData.Application.ActiveUIDocument.Document;
			Result result;
			try
			{
				if (cmdData == null)
				{
					throw new System.ArgumentNullException("commandData");
				}
				this.m_Revit = cmdData;
				try
				{
					WallJoinOperator wallJoinOperator = new WallJoinOperator();
					while (wallJoinOperator.SetSingleUnJoinWall(this.m_Revit))
					{
					}
				}
				catch (Exception)
				{
					return Autodesk.Revit.UI.Result.Failed;
				}
				result = Autodesk.Revit.UI.Result.Succeeded;
			}
			catch (Exception ex)
			{
				msg = ex.Message;
				result = Autodesk.Revit.UI.Result.Failed;
			}
			return result;
		}

		public static WindowHandle _hWndRevit;

		private ExternalCommandData m_Revit;
	}
}
